
/*****联动配置 2017-06-08**************/
cBoard.controller('linkageFormCtrl', function ($scope, $stateParams, $http, $uibModal, dataService, ModalUtils, updateService, $filter, chartService, $timeout,$location) {
    $("#link").addClass("active");
    var translate = $filter('translate');
    var id = $stateParams.id;
    var updateUrl = "dashboard/updateWidget.do";
    $scope.widgetList=[];
    $scope.datasetList=[];
    $scope.curLinkageWidget={};
    $scope.curByLinkageWidget={};

    /**获取图表资源
    * */
    var getWidgetList = function (callback) {
        $http.get("dashboard/getWidgetList.do").success(function (response) {
            if(response){
                $scope.widgetList = response;
                $scope.linkageWidgetList = [];
                $scope.linkageWidgetList = _.filter($scope.widgetList,function(param){
                    return (param.data.config.keys.length!=0)
                })
                if (callback) {
                    callback();
                }
                if(id){
                    getWidgetLink(id);
                }
            }else{
                $scope.widgetList =[];
            }

        });
    };
    // 获得联动信息
    var getWidgetLink =function(id){

        $http.post("admin/getWidgetLink.do",{"id":id}).success(function (response) {
            $scope.widgetLink = response;
            //
            //var linkWidget = _.find($scope.widgetList,function(param){
            //    return param.id == response.activeWidgetId;
            //});
            $scope.linkageWidget =$scope.widgetLink.activeWidgetId;
            $scope.changeWidget();
            $scope.linkCol=[];
            $scope.bylinkCol=[];
            var activeWidgetConfig = angular.fromJson($scope.widgetLink.activeWidgetConfig);
            _.each(activeWidgetConfig,function(param){
                $scope.linkCol.push({"id":param.col,"text":param.col});
            })

            $scope.bylinkageWidget =$scope.widgetLink.passiveWidgetId;
            $scope.changeByWidget();
            var passiveWidgetConfig = angular.fromJson($scope.widgetLink.passiveWidgetConfig);
            _.each(passiveWidgetConfig,function(param){
                $scope.bylinkCol.push({"id":param.col,"text":param.col});
            })
            //var activeWidgetConfig =eval(response.activeWidgetConfig);
            //_.each(activeWidgetConfig,function(data){
            //
            //    $scope.linkageArr.push({
            //        widgetId:response.activeWidgetId,
            //        // alias: "",
            //        col: data.col,
            //        //level: item.level,
            //        //type: 'eq',
            //        widget:linkWidget.data,
            //    });
            //})
            //var bylinkWidget = _.find($scope.widgetList,function(param){
            //    return param.id == response.passiveWidgetId;
            //});
            //$scope.bylinkName = bylinkWidget.categoryName+"/"+bylinkWidget.name;
            //var passiveWidgetConfig = eval(response.passiveWidgetConfig);
            //_.each(passiveWidgetConfig,function(data){
            //    $scope.bylinkageArr.push({
            //        widgetId:response.passiveWidgetId,
            //        // alias: "",
            //        col: data.col,
            //        //level: item.level,
            //        //type: 'eq',
            //        widget:bylinkWidget.data,
            //    });
            //})

        });
    }



    /**
     * 获得数据集
     * **/
    var getDataset = function (callback) {
        $http.get("dashboard/getDatasetList.do").success(function (response) {
            $scope.datasetList = response;
            if (callback) {
                callback();
            }
        });
    };
    /**
     * 通过数据集Id获得数据集信息
     * **/
    var getDatasetById = function (id) {
        var dataset = _.find($scope.datasetList, function (w) {
            return w.id == id;
        })
        return dataset;
    };
    /**
     * 通过数据集Id获得数据集信息
     * **/
    var getWidgetById = function (id) {
        var widget = _.find($scope.widgetList, function (w) {
            return w.id == id;
        })
        return widget;
    };
    getWidgetList();
    getDataset();

    /**
     * 选择图表事件
     * */
    $scope.linkageCol={data:[]};
    $scope.bylinkageCol={data:[]};
    $scope.bylinkageWidgetList = [];
    $scope.loadData=function(){

    }
    $scope.changeWidget=function(){
        $scope.linkageCol={data:[]};
        var widget = getWidgetById($scope.linkageWidget);
        var arr = [];
        _.each(widget.data.config.keys,function(param){

            arr.push({id:param.col,text:param.col});
        })
        $scope.linkageCol.data=arr;
       // $scope.bylinkageWidgetList =$scope.widgetList;
    }
    $scope.changeByWidget=function(){
        $scope.bylinkageCol.data = {data:[]};;
        var widget = getWidgetById($scope.bylinkageWidget);

        var datasetId = widget.data.datasetId;
        var dataset = getDatasetById(datasetId);
        var datasourceId = dataset.data.datasource;
        var query = dataset.data.query;
        $http.post("dashboard/getColumns.do", {
            datasourceId:datasourceId,
            query: query,
            datasetId: datasetId,
            reload:""
        }).success(function (response) {
            var arr = [];
            _.each(response.columns,function(param){

                arr.push({id:param,text:param});
            })
            $scope.bylinkageCol.data = arr;
        });
    }
    var getColumn=function(obj){
        var arr = [];
        _.each(obj,function(param){

            arr.push(param.text);
        });
        return arr;
    }
    function validate(){
        if(!$scope.linkageWidget){
            ModalUtils.alert("请选择联动图表", "modal-danger", "lg");
            return false;
        }
        if(!$scope.linkCol){
            ModalUtils.alert("请设置联动列名", "modal-danger", "lg");
            return false;
        }
        if(!$scope.bylinkageWidget){
            ModalUtils.alert("请选择被联动图表", "modal-danger", "lg");
            return false;
        }
        if(!$scope.bylinkCol){
            ModalUtils.alert("请设置被联动列名", "modal-danger", "lg");
            return false;
        }
        if($scope.linkageWidget == $scope.bylinkageWidget){
            ModalUtils.alert("联动图表和被联动图表不能为同一个图表", "modal-danger", "lg");
            return false;
        }
        return true;
    }
    /**预览**/
    $scope.preview = function () {
        if(!validate()){
            return false;
        }
        //获得联动图表图表信息（widget）
        $scope.linkageWidgetConfig = _.find($scope.widgetList, function (w) {
            return w.id == $scope.linkageWidget;
        });

        //获得被联动图表图表信息（widget）
        $scope.bylinkageWidgetConfig = _.find($scope.widgetList, function (w) {
            return w.id == $scope.bylinkageWidget;
        });
        ;
        $scope.loadingPre = true;
        //获得被联动图表字段
        var bylinkageArr = getColumn($scope.bylinkCol);
        var datasetId = $scope.linkageWidgetConfig.data.datasetId;
        var dataset = getDatasetById(datasetId);
        var datasourceId = dataset.data.datasource;
        var query = dataset.data.query;
        //绘制联动图表
        chartService.render($('#preview_widget'), {
            linkageInfo:{"bylinkage":bylinkageArr,"bylinkage":$scope.bylinkageWidgetConfig,"bylinkageId":$scope.bylinkageWidget,"linkageWidgetId":$scope.linkageWidget,"object":$('#preview_widget1')},
            config: $scope.linkageWidgetConfig.data.config,
            datasource: datasourceId,
            query: query,
            datasetId: datasetId
        }, function (option) {
            $scope.previewDivWidth = 12;
            option.toolbox = {
                feature: {
                    dataView: {
                        show: true,
                        readOnly: true
                    }
                }
            };
            $scope.loadingPre = false;
        }, null, !$scope.loadFromCache);
        var byDatasetId = $scope.bylinkageWidgetConfig.data.datasetId;
        var byDataset = getDatasetById(byDatasetId);
        var byDatasourceId = byDataset.data.datasource;
        var byQuery = byDataset.data.query;
        //绘制被联动图表
        chartService.render($('#preview_widget1'), {
            config: $scope.bylinkageWidgetConfig.data.config,
            datasource: byDatasourceId,
            query:byQuery,
            datasetId: byDatasetId
        }, function (option) {
                    $scope.previewDivWidth1 = 12;
                    option.toolbox = {
                        feature: {
                            dataView: {
                                show: true,
                                readOnly: true
                            }
                        }
                    };
            $scope.loadingPre = false;
        }, null, !$scope.loadFromCache);
    };
    //保存数据
    $scope.saveWgt=function(){
        if(!validate()){
            return false;
        }
        var linkColArr = [];
        var bylinkColArr = [];
        angular.forEach($scope.linkCol,function(data,index){
            linkColArr.push({"widgetId":$scope.linkageWidget,"col":data.text});
        });
        angular.forEach($scope.bylinkCol,function(data,index){
            bylinkColArr.push({"widgetId":$scope.bylinkageWidget,"col":data.text});
        });
        var param =angular.toJson({"id":id,"activeWidgetId":$scope.linkageWidget,"passiveWidgetId":$scope.bylinkageWidget,"activeWidgetConfig": linkColArr,"passiveWidgetConfig":bylinkColArr});
        $http.post("admin/saveOrUpdateLink.do",{"link":param}).success(function (response) {
            if(response.status == 1){
                $location.path('/config/linkage');
            }else{
                $scope.alerts = [{msg: response.msg, type: 'danger'}];
            }
        });
    }
    //取消设置，返回列表
    $scope.cancel=function(){
        $location.path('/config/linkage');
    }
});
